package com.tedu.store.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.security.MessageDigest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.tedu.store.vdcode.ImageUtil;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import com.tedu.store.entity.User;

import com.tedu.store.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController {
	
	@Autowired
	private UserService userService;

	//实现验证手机验证码功能
		@RequestMapping(value="/telLogin",method=RequestMethod.GET)
		public ModelAndView telLogin(String tel,String tcode,
				HttpSession session, HttpServletRequest request) throws Exception {
			ModelAndView modelAndView = new ModelAndView();
			String alertMsg="";
			String t_tel="";
			String t_telCode="";
			Cookie[] cookies = request.getCookies();
			for(Cookie cookie : cookies){
			    if(cookie.getName().equals("tel_telCode")){
			    	String msg=cookie.getValue();
			        t_tel=msg.split("&")[0];
			        t_telCode=msg.split("&")[1];
			        break;
			    }
			}
			if (tcode.equals(t_telCode)&&
				tel.equals(t_tel)){
				if(userService.getUserByName(tel)==null){
					alertMsg="*您还没有注册*";
					session.setAttribute("alertMsg", alertMsg);
					modelAndView.setViewName("redirect:/login.jsp");
					return modelAndView;
				}else{
					session.setAttribute("user", userService.getUserByName(tel));
					modelAndView.setViewName("redirect:/product/getIndexProducts.do");
				}
			}else{
				alertMsg="*验证码错误或已失效*";
				modelAndView.setViewName("redirect:/login.jsp");
			}
			session.setAttribute("alertMsg", alertMsg);
			session.setAttribute("username", tel);
				return modelAndView;
			}
			
	//实现验证手机验证码功能
		@RequestMapping(value="/validateCode",method=RequestMethod.POST)
		public ModelAndView validateCode(String tel,String code,HttpSession session, HttpServletRequest request) throws Exception {
			ModelAndView modelAndView = new ModelAndView();
			    String alertMsg="";
			    String t_tel="";
			    String t_telCode="";
			    Cookie[] cookies = request.getCookies();
			    for(Cookie cookie : cookies){
			        if(cookie.getName().equals("tel_telCode")){
			        	String msg=cookie.getValue();
			        	t_tel=msg.split("&")[0];
			        	t_telCode=msg.split("&")[1];
			        	break;
			        }
			     }
			    if(t_tel.equals("")){
			    	alertMsg="*验证码已失效*";
			    	session.setAttribute("alertMsg", alertMsg);
					modelAndView.setViewName("redirect:/login.jsp");
					return modelAndView;
			    }
			   if (request.getParameter("action").equals("regist")){
				   if (code.equals(t_telCode)&&
							tel.equals(t_tel)){
					   		session.setAttribute("action", "register");
							modelAndView.setViewName("redirect:/setPassword.jsp");
				   }else{
							alertMsg="*验证码错误*";
							modelAndView.setViewName("redirect:/regist.jsp");
					}
			   }else{
				   if (code.equals(t_telCode)&&
							tel.equals(t_tel)){
					   		session.setAttribute("action", "updatePassword");
							modelAndView.setViewName("redirect:/setPassword.jsp");
				   }else{
							alertMsg="*验证码错误*";
							modelAndView.setViewName("redirect:/regist.jsp");
					}
			   }
			
			session.setAttribute("alertMsg", alertMsg);
			session.setAttribute("username", tel);
			return modelAndView;
		}
		
		
	//实现用户自行注册功能
	@RequestMapping(value="/register",method=RequestMethod.POST)
	public ModelAndView insert(HttpServletRequest request,HttpSession session) throws Exception {
		ModelAndView modelAndView = new ModelAndView();
		User user=new User();
		user.setUsername(request.getParameter("username"));
		user.setPassword(request.getParameter("password"));
		user.setMoney(0);
		user.setScore(0);
		if (request.getParameter("usertype")==null){
			user.setUsertype("user");
			user.setState(1);
			Date date=new Date();
			user.setRegistTime(date);
			userService.insertUser(user);
			User temp=new User();
			temp=userService.getUserByName(user.getUsername());
			System.out.println(temp.getUserID());

			String alertMsg="*注册成功*";
			session.setAttribute("alertMsg", alertMsg);
			modelAndView.setViewName("redirect:/login.jsp");
			return modelAndView;
		}else{
			if (request.getParameter("usertype").equals("admin")){
				user.setUsertype("admin");
			}else if(request.getParameter("usertype").equals("sAdmin")){
				user.setUsertype("sAdmin");
			}else if(request.getParameter("usertype").equals("service")){
				user.setUsertype("service");
			}else{
				user.setUsertype("user");
			}
		}
		
		user.setState(1);
		Date date=new Date();
		user.setRegistTime(date);
		String alertMsg="";			
		if (userService.insertUser(user)){

			alertMsg="*注册成功*";

		}else{
			alertMsg="*注册失败,用户名重复*";
		}
		session.setAttribute("alertMsg", alertMsg);
		if (request.getParameter("usertype").equals("user")){
			modelAndView.setViewName("redirect:/login.jsp");
		}else{
			modelAndView.setViewName("redirect:/user/getAllSysUsers.do");
		}
		
		return modelAndView;
	}
	
	//发送短信验证码
	@RequestMapping(value="/sendMessage",method=RequestMethod.GET)
	public String send(String tel
			,HttpSession session, HttpServletResponse response) throws Exception {
		String uid="suxiangrui";
		String pwd="0fa33b2309a37ca211d696e3698fe9f6";
		String telCode=String.valueOf((int)(Math.random()*1000000+1));
		String text="{\"code\":\""+telCode+"\"}";
		String code=java.net.URLEncoder.encode(text);
		String template="100006";
		String url="http://api.sms.cn/sms/?ac=send&uid="+uid+"&pwd="+pwd+"&template="+template+"&mobile="+tel+"&content="+code;
		
		//设置Cookie保存手机和手机验证码
		String tel_telCode = tel + "&" + telCode;
		Cookie cookie = new Cookie("tel_telCode", tel_telCode);
		cookie.setMaxAge(5 * 60);
        response.addCookie(cookie);
        
		return "redirect:"+url;
	}
	
	//实现用户登录功能
	@RequestMapping(value="/login",method=RequestMethod.POST)
	public ModelAndView login(String username,String password,String usertype,String code
			,HttpSession session,HttpServletResponse response) throws IOException{
		ModelAndView modelAndView = new ModelAndView();
		
		if(userService.getUserByName(username)==null){
			session.setAttribute("alertMsg", "*账户不存在*");
			modelAndView.setViewName("redirect:/login.jsp");
			return modelAndView;
		}
		User user=new User();
		user.setUsername(username);
		user.setPassword(password);
		user.setUsertype(usertype);
		String vdcode=(String) session.getAttribute("imageCode");
		if (vdcode.equals(code)){
			if (userService.validate(user)){
				session.setAttribute("user", userService.getUserByName(username));//绑定登录用户
				modelAndView.setViewName("redirect:/product/getIndexProducts.do");
			}else{
				session.setAttribute("alertMsg", "*用户名或密码错误*");
				modelAndView.setViewName("redirect:/login.jsp");		
			}
		}else{
			session.setAttribute("alertMsg", "*验证码错误*");
			modelAndView.setViewName("redirect:/login.jsp");
		}
		
		return modelAndView;
	}
	
	//实现管理员登录功能
		@RequestMapping(value="/backLogin",method=RequestMethod.POST)
		public ModelAndView backLogin(String username,String password,String usertype,HttpSession session,HttpServletResponse response) throws IOException{
			ModelAndView modelAndView = new ModelAndView();
			
			if(userService.getUserByName(username)==null){
				session.setAttribute("alertMsg", "*账户不存在*");
				modelAndView.setViewName("redirect:/backLogin.jsp");
				return modelAndView;
			}
			User user=new User();
			user.setUsername(username);
			user.setPassword(password);
			user.setUsertype(usertype);
			if (userService.validate(user)){
				session.setAttribute("user", userService.getUserByName(username));//绑定登录用户
				if (user.getUsertype().equals("sAdmin")){
					modelAndView.setViewName("redirect:/manager_protect/sIndex.jsp");
				}else{
					modelAndView.setViewName("redirect:/manager_protect/index.jsp");
				}
				
			}else{
				session.setAttribute("alertMsg", "*用户名或密码错误*");
				modelAndView.setViewName("redirect:/backLogin.jsp");		
			}
			
			return modelAndView;
		}
		
		//超级管理员获取所有用户的信息
		@RequestMapping(value="/getAllUsers",method=RequestMethod.GET)
		public String getAllUsers(HttpServletRequest request,HttpSession session){
			String view="";
			List<User> users=userService.getAllUsers();
			for(User user:users){
				String t=user.getPassword();
				user.setPassword(md5(t));
			}
			session.setAttribute("users", users);
			view="redirect:/manager_protect/userList.jsp";
			return view;
		}
		
		//超级管理员获取所有用户的信息
				@RequestMapping(value="/getAllSysUsers",method=RequestMethod.GET)
				public String getAllSysUsers(HttpServletRequest request,HttpSession session){
					String view="";
					List<User> sysUsers=userService.getAllSysUsers();
					session.setAttribute("sysUsers", sysUsers);
					view="redirect:/manager_protect/sysUserList.jsp";
					return view;
				}
		
		//超级管理员获取所有用户的信息
		@RequestMapping(value="/getUserById",method=RequestMethod.GET)
		public String getUserById(int userID,HttpServletRequest request,HttpSession session){
			String view="";
			User t_user=userService.getUserById(userID);
//			String t=t_user.getPassword();
//			t_user.setPassword(md5(t));
			session.setAttribute("t_user", t_user);
			session.setAttribute("registTime", t_user.getRegistTime());
			view="redirect:/manager_protect/modifyUser.jsp";
			return view;
		}
		
		@RequestMapping(value="/modifyUser",method=RequestMethod.POST)
		public String modifyUser(HttpServletRequest request,HttpSession session) throws ParseException{
			String view="";
			User user=new User();
			user.setUserID(Integer.parseInt(request.getParameter("userID")));
			user.setUsername(request.getParameter("username"));
			user.setPassword(request.getParameter("password"));
			user.setScore(Integer.parseInt(request.getParameter("score")));
			
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
			Date date = sdf.parse((String) session.getAttribute("registTime")); 
			user.setRegistTime(date);
			user.setState(Integer.parseInt(request.getParameter("state")));
			user.setUsertype(request.getParameter("usertype"));
			user.setMoney(Float.parseFloat(request.getParameter("money")));
			userService.modifyUser(user);
			User t_user=(User) session.getAttribute("user");
			if (t_user.getUsertype().equals("admin")){
				view="redirect:/user/getAllUsers.do";
			}else{
				view="redirect:/user/getAllSysUsers.do";
			}
			return view;
		}
		
		@RequestMapping(value="/deleteUser",method=RequestMethod.GET)
		public String deleteUser(int userID,HttpSession session) throws ParseException{
			String view="";
			userService.deleteUser(userID);
			view="redirect:/user/getAllUsers.do";
			return view;
		}
		
	@RequestMapping(value="/updatePassword",method=RequestMethod.POST)
	public String updatePassword(HttpServletRequest request,HttpSession session){
		String view="";
		User user=new User();
		user.setUsername((String) session.getAttribute("username"));
		System.out.println(request.getParameter("username"));
		user.setPassword(request.getParameter("password"));
		System.out.println(request.getParameter("password"));
		userService.updatePassword(user);
		session.removeAttribute("username");
		session.removeAttribute("user");
		session.setAttribute("alertMsg", "*修改密码成功,请重新登录*");
		view="redirect:/login.jsp";
		return view;
	}
	
	
	//用户注销登录
	@RequestMapping("/logoff.do")
	public String logoff(
		HttpSession session)throws IOException{
		if ((User) session.getAttribute("user")==null){
			return "redirect:/login.jsp";
		}
		User user=(User) session.getAttribute("user");
		if (user.getUsertype().equals("user")){
			session.removeAttribute("user");
			return "redirect:/login.jsp";
		}else{
			session.removeAttribute("user");
			return "redirect:/backLogin.jsp";
		}
		
	}
	
	
	
	
	
	
	@RequestMapping("/createImage.do")
	public void createImage(
		HttpServletResponse response,HttpSession session)throws IOException{
		Map<String,BufferedImage> imageMap=ImageUtil.createImage();
		String code=imageMap.keySet().iterator().next();
		session.setAttribute("imageCode", code);
		BufferedImage image=imageMap.get(code);
 		ServletOutputStream out=response.getOutputStream();
		ImageIO.write(image, "jpeg", out);
		out.close();	
	}
	
	
	public static String md5(String str){		
		//首先利用MD5算法将密码加密，变成等长字节
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] b1 = md.digest(str.getBytes());
			//将等长字节利用Base64算法转换成字符串
			BASE64Encoder encoder = new BASE64Encoder();
			return encoder.encode(b1);
		} catch (Exception e) {
			return null;
		}
	}
	
	public static void de(String base){
		System.out.println(base);
		BASE64Encoder encoder = new BASE64Encoder();
		String bb = encoder.encode(base.getBytes());
		System.out.println(bb);
		BASE64Decoder decoder = new BASE64Decoder();
		try {
			byte[] b1 = decoder.decodeBuffer(bb);
			System.out.println(b1);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
}
